#!/bin/bash

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量
INSTALL_DIR="/opt/cmdb-agent"
CONFIG_DIR="${INSTALL_DIR}/etc"
SERVICE_NAME="cmdb-agent"
DOWNLOAD_BASE_URL="https://123pan.bkdomain.cn/cmdb/cmdb-agent"
BINARY_URL="${DOWNLOAD_BASE_URL}/cmdb-agent"
CONFIG_URL="${DOWNLOAD_BASE_URL}/config.yml"

function log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

function log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

function log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

function log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

function check_root() {
    if [ "$EUID" -ne 0 ]; then
        log_error "请使用 root 权限运行此脚本"
        exit 1
    fi
}

function check_system() {
    log_step "检查系统环境..."
    
    if [ ! -f /etc/os-release ]; then
        log_error "无法识别操作系统"
        exit 1
    fi
    
    . /etc/os-release
    log_info "操作系统: ${PRETTY_NAME}"
    
    if ! command -v systemctl &> /dev/null; then
        log_error "系统不支持 systemd，无法安装服务"
        exit 1
    fi
}

function stop_service() {
    log_step "停止旧服务..."
    
    if systemctl is-active --quiet ${SERVICE_NAME}; then
        log_info "停止 ${SERVICE_NAME} 服务..."
        systemctl stop ${SERVICE_NAME}
    fi
    
    if systemctl is-enabled --quiet ${SERVICE_NAME} 2>/dev/null; then
        log_info "禁用 ${SERVICE_NAME} 服务..."
        systemctl disable ${SERVICE_NAME}
    fi
}

function download_files() {
    log_step "下载 cmdb-agent 文件..."
    
    # 创建安装目录和配置目录
    mkdir -p ${INSTALL_DIR}
    mkdir -p ${CONFIG_DIR}
    
    # 下载二进制文件
    log_info "下载二进制文件: ${BINARY_URL}"
    if command -v wget &> /dev/null; then
        wget -O ${INSTALL_DIR}/cmdb-agent ${BINARY_URL} || {
            log_error "下载二进制文件失败"
            exit 1
        }
    elif command -v curl &> /dev/null; then
        curl -L -o ${INSTALL_DIR}/cmdb-agent ${BINARY_URL} || {
            log_error "下载二进制文件失败"
            exit 1
        }
    else
        log_error "未找到 wget 或 curl 命令，请先安装"
        exit 1
    fi
    
    # 设置可执行权限
    chmod +x ${INSTALL_DIR}/cmdb-agent
    log_info "二进制文件下载完成"
    
    # 下载配置文件（如果不存在）
    if [ ! -f ${CONFIG_DIR}/config.yml ]; then
        log_info "下载配置文件: ${CONFIG_URL}"
        if command -v wget &> /dev/null; then
            wget -O ${CONFIG_DIR}/config.yml ${CONFIG_URL} || {
                log_warn "下载配置文件失败，请手动配置"
            }
        elif command -v curl &> /dev/null; then
            curl -L -o ${CONFIG_DIR}/config.yml ${CONFIG_URL} || {
                log_warn "下载配置文件失败，请手动配置"
            }
        fi
    else
        log_warn "配置文件已存在，跳过下载（保留现有配置）"
    fi
}

function install_service() {
    log_step "安装 systemd 服务..."
    
    # 创建 systemd 服务文件
    cat > /etc/systemd/system/${SERVICE_NAME}.service <<EOF
[Unit]
Description=CMDB Agent Service
Documentation=https://github.com/linkfog/cmdb-agent
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=root
Group=root
WorkingDirectory=${INSTALL_DIR}
ExecStart=${INSTALL_DIR}/cmdb-agent -f ${CONFIG_DIR}/config.yml
Restart=always
RestartSec=10s
LimitNOFILE=65536
StandardOutput=journal
StandardError=journal
SyslogIdentifier=${SERVICE_NAME}

# 安全配置
ProtectSystem=full
ProtectHome=true
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
EOF
    
    log_info "systemd 服务文件已创建"
}

function start_service() {
    log_step "启动服务..."
    
    # 重新加载 systemd 配置
    systemctl daemon-reload
    
    # 启用服务
    systemctl enable ${SERVICE_NAME}
    log_info "服务已设置为开机自启动"
    
    # 启动服务
    systemctl start ${SERVICE_NAME}
    
    # 等待服务启动
    sleep 2
    
    # 检查服务状态
    if systemctl is-active --quiet ${SERVICE_NAME}; then
        log_info "服务启动成功！"
    else
        log_error "服务启动失败，请检查日志: journalctl -u ${SERVICE_NAME} -f"
        exit 1
    fi
}

function show_status() {
    log_step "服务状态..."
    echo ""
    systemctl status ${SERVICE_NAME} --no-pager || true
    echo ""
    log_info "安装完成！"
    echo ""
    echo -e "${BLUE}常用命令:${NC}"
    echo "  启动服务: systemctl start ${SERVICE_NAME}"
    echo "  停止服务: systemctl stop ${SERVICE_NAME}"
    echo "  重启服务: systemctl restart ${SERVICE_NAME}"
    echo "  查看状态: systemctl status ${SERVICE_NAME}"
    echo "  查看日志: journalctl -u ${SERVICE_NAME} -f"
    echo "  配置文件: ${CONFIG_DIR}/config.yml"
    echo ""
}

function main() {
    echo -e "${BLUE}================================${NC}"
    echo -e "${BLUE}   CMDB Agent 安装脚本${NC}"
    echo -e "${BLUE}================================${NC}"
    echo ""
    
    check_root
    check_system
    stop_service
    download_files
    install_service
    start_service
    show_status
}

main